package com.eedi.framework.oauth2.controller.org;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.eedi.framework.common.enums.CommonStatusEnum;
import com.eedi.framework.common.pojo.CommonResult;
import com.eedi.framework.logger.enmus.SysLoginLogTypeEnum;
import com.eedi.framework.oauth2.controller.org.vo.auth.OrgAuthLoginReq;
import com.eedi.framework.oauth2.controller.org.vo.auth.OrgAuthLoginResp;
import com.eedi.framework.oauth2.controller.org.vo.auth.OrgAuthPermissionInfoResp;
import com.eedi.framework.oauth2.convert.OrgAuthConvert;
import com.eedi.framework.oauth2.service.OrgAuthService;
import com.eedi.framework.oauth2.service.OrgOAuth2ClientService;
import com.eedi.framework.permission.dal.dataobject.OrgMenuDO;
import com.eedi.framework.permission.dal.dataobject.OrgRoleDO;
import com.eedi.framework.permission.service.OrgPermissionService;
import com.eedi.framework.security.config.SecurityProperties;
import com.eedi.framework.security.core.util.SecurityFrameworkUtils;
import com.eedi.framework.user.controller.org.vo.OrgUserLoginInfoResp;
import com.eedi.framework.user.service.OrgUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import static com.eedi.framework.common.pojo.CommonResult.success;
import static com.eedi.framework.common.util.collection.CollectionUtils.convertSet;
import static com.eedi.framework.security.core.util.SecurityFrameworkUtils.*;

/**
 * @author liuyf
 */
@Tag(name = "经营界面 - 认证")
@RestController
@RequestMapping("/org/auth")
@Validated
@Slf4j
public class OrgAuthController {
    @Resource
    OrgAuthService orgAuthService;
    @Resource
    SecurityProperties securityProperties;

    @Resource
    OrgUserService orgUserService;

    @Resource
    OrgPermissionService orgPermissionService;

    @Resource
    OrgOAuth2ClientService orgOAuth2ClientService;


    @PostMapping("/login")
    @PermitAll
    @Operation(summary = "使用账号密码登录")
    public CommonResult<OrgAuthLoginResp> login(@RequestBody @Valid OrgAuthLoginReq reqVO) {
        //根据当前租户ID获取clientId，仅适用于单体式架构
        if (StrUtil.isBlank(reqVO.getOrgClientId())){
            reqVO.setOrgClientId(orgOAuth2ClientService.getClientIdByOrginfoId(getOrgInfoId()));
        }
        return success(orgAuthService.login(reqVO));
    }

    @PostMapping("/logout")
    @PermitAll
    @Operation(summary = "登出系统")
    public CommonResult<Boolean> logout(HttpServletRequest request) {
        String token = SecurityFrameworkUtils.obtainAuthorization(request,
                securityProperties.getTokenHeader(), securityProperties.getTokenParameter());
        if (StrUtil.isNotBlank(token)) {
            orgAuthService.logout(token, SysLoginLogTypeEnum.LOGOUT_SELF);
        }
        return success(true);
    }

    @PostMapping("/refresh-token")
    @PermitAll
    @Operation(summary = "刷新令牌")
    @Parameter(name = "refreshToken", description = "刷新令牌", required = true)
    public CommonResult<OrgAuthLoginResp> refreshToken(@RequestParam("refreshToken") String refreshToken) {
        //根据当前租户ID获取clientId，仅适用于单体式架构
        String sysClientId = orgOAuth2ClientService.getClientIdByOrginfoId(getOrgInfoId());
        return success(orgAuthService.refreshToken(refreshToken,sysClientId));
    }

    @GetMapping("/get-permission-info")
    @Operation(summary = "获取登录用户的权限信息")
    public CommonResult<OrgAuthPermissionInfoResp> getPermissionInfo() {
        // 1.1 获得用户信息
        OrgUserLoginInfoResp logininfo = orgUserService.selectByOrgUserId(getLoginUserId());
        if (logininfo == null) {
            return success(null);
        }

        // 1.2 获得角色列表
        Set<String> roleIds = orgPermissionService.getUserRoleIdListByUserId(getLoginUserId());
        if (CollUtil.isEmpty(roleIds)) {
            return success(OrgAuthConvert.INSTANCE.convert(logininfo, Collections.emptyList(), Collections.emptyList()));
        }
        List<OrgRoleDO> roles = orgPermissionService.getRoleList(roleIds);
        // 移除禁用的角色
        roles.removeIf(role -> !CommonStatusEnum.ENABLE.equals(role.getOrgRoleStatus()));

        // 1.3 获得菜单列表
        Set<String> menuIds = orgPermissionService.getRoleMenuListByRoleId(convertSet(roles, OrgRoleDO::getOrgRoleId));
        List<OrgMenuDO> menuList = orgPermissionService.getMenuList(menuIds);
        // 移除禁用的菜单
        menuList.removeIf(menu -> !CommonStatusEnum.ENABLE.equals(menu.getOrgMenuStatus()));

        // 2. 拼接结果返回
        return success(OrgAuthConvert.INSTANCE.convert(logininfo, roles, menuList));
    }

    @GetMapping("/get-menu-info")
    @Operation(summary = "获取登录用户的菜单信息")
    public CommonResult<List<OrgAuthPermissionInfoResp.MenuVO>> getMenuInfo() {
        // 1 获得角色列表
        Set<String> roleIds = orgPermissionService.getUserRoleIdListByUserId(getLoginUserId());
        List<OrgRoleDO> roles = orgPermissionService.getRoleList(roleIds);
        // 2 移除禁用的角色
        roles.removeIf(role -> !CommonStatusEnum.ENABLE.equals(role.getOrgRoleStatus()));
        // 3 获得菜单列表
        Set<String> menuIds = orgPermissionService.getRoleMenuListByRoleId(convertSet(roles, OrgRoleDO::getOrgRoleId));
        List<OrgMenuDO> menuList = orgPermissionService.getMenuList(menuIds);
        // 4 移除禁用的菜单
        menuList.removeIf(menu -> !CommonStatusEnum.ENABLE.equals(menu.getOrgMenuStatus()));

        // 2. 拼接结果返回
        return success(OrgAuthConvert.INSTANCE.buildMenuTree(menuList));
    }
}
